package controllers

import (
	"encoding/json"
	"net/http"

	"git.oschina.net/Ljohn/softCup/lib"
	"git.oschina.net/Ljohn/softCup/models"
	"git.oschina.net/Ljohn/softCup/conf"
	"git.oschina.net/Ljohn/softCup/sys"
	"errors"
	"fmt"
)



//GetPrivateToken ...
func GetProjectList(w http.ResponseWriter, req *http.Request) {

	privateToken, err := lib.GetRawQueryByArgs(req.URL.RawQuery, "pri_token")
	if err != nil {
		lib.HandleError(err)
		w.Write(models.GetErrorResult("私有token未获取到"))
		return
	}
	url := conf.GitlabURL()+ "/api/v3/projects?private_token=" + privateToken
	_,res, head,err:= lib.HttpRequest(url, "GET", nil, nil)
	if err !=nil{
		lib.HandleError(err)
		w.Write(models.GetFalatResult())
		return
	}

	if head.Get("Status") != "200 OK" {
		w.Write(models.GetFalatResult())
		return
	}

	str := lib.Json(string(res))
	modelArr := str.GetGitlabProjectModel()
	temp, err := json.Marshal(modelArr)
	if err != nil {
		lib.HandleError(err)
		w.Write(models.GetFalatResult())
		return
	}
	resModel, err := models.SetResult(200, "succ", string(temp))
	if err != nil {
		lib.HandleError(err)
		w.Write(models.GetFalatResult())
		return
	}
	w.Write(resModel)
}

func SignUpOver(w http.ResponseWriter, req *http.Request) {

	privateToken, err := lib.GetHeaderToken(req)
	if err != nil {
		lib.HandleError(err)
		w.Write(models.GetErrorResult("私有token未获取到"))
		return
	}
	if privateToken != "11qq22e"{
		lib.HandleError(err)
		w.Write(models.GetErrorResult("未通过验证"))
		return
	}
	FixSign()
	resModel, err := models.SetResult(200, "停止成功", "")
	if err != nil {
		lib.HandleError(err)
		w.Write(models.GetFalatResult())
		return
	}
	w.Write(resModel)
}

func GetProjectBranch(w http.ResponseWriter, req *http.Request) {

	privateToken, err := lib.GetRawQueryByArgs(req.URL.RawQuery, "pri_token")
	if err != nil {
		lib.HandleError(err)
		w.Write(models.GetErrorResult("参数错误"))
		return
	}
	projectID, err := lib.GetRawQueryByArgs(req.URL.RawQuery, "id")
	if err != nil {
		lib.HandleError(err)
		w.Write(models.GetErrorResult("参数错误"))
		return
	}
	url := conf.GitlabURL()+ "/api/v3/projects/" + projectID + "/repository/branches?private_token=" + privateToken
	_,res, head,err := lib.HttpRequest(url, "GET", nil, nil)
	if err != nil{
		lib.HandleError(err)
		w.Write(models.GetFalatResult())
		return
	}

	if head.Get("Status") != "200 OK" {
		w.Write(models.GetErrorResult("请求错误"))
		return
	}
	temp := &[]models.ApiGitlabBranch{}
	err = json.Unmarshal(res, temp)
	if err != nil {
		lib.HandleError(err)
		w.Write(models.GetErrorResult("转换JSON 失败"))
		return
	}

	resultStr := make([]string, len(*temp))
	for i, k := range *temp {
		//fmt.Println(i, "....", k.Name)
		resultStr[i] = k.Name
	}

	resModel, err := models.SetResult(200, "succ", resultStr)
	if err != nil {
		lib.HandleError(err)
		w.Write(models.GetFalatResult())
		return
	}
	w.Write(resModel)
}


func GetRepertoryList(w http.ResponseWriter,req *http.Request){
	uid, err := lib.GetRawQueryByArgs(req.URL.RawQuery, "uid")
	if err != nil {
		lib.HandleError(err)
		w.Write(models.GetErrorResult("参数错误"))
		return
	}
	urlPl := conf.MicroServerURL()+ "/manage/api/select_pro_username?request_token=" + "11qq22e"+"&uid="+uid
	_,testBody, _ ,err:= lib.HttpRequest(urlPl, "GET", nil, nil)
	if err !=nil{
		lib.HandleError(err)
		w.Write(models.GetFalatResult())
		return
	}
	resTemp := &models.ApiRes{}
	err = json.Unmarshal(testBody, resTemp)
	if err !=nil{
		lib.HandleError(err)
		w.Write(models.GetErrorResult("转换JSON失败"))
		return
	}
	if len(resTemp.Data.Pro_info)==0{
		lib.HandleError(errors.New("未找到对象"))
		w.Write(models.GetErrorResult("未找到对象"))
		return
	}
	username := resTemp.Data.Pro_info[0].Pro_username
	res,err := sys.GetRepertoryList(username)
	if err !=nil {
		lib.HandleError(err)
		w.Write(models.GetErrorResult(err.Error()))
		return
	}
	resModel, err := models.SetResult(200, "succ", string(res))
	if err != nil {
		lib.HandleError(err)
		w.Write(models.GetFalatResult())
		return
	}
	w.Write(resModel)
}


func BuildProject(w http.ResponseWriter,req *http.Request){
	uid, err := lib.GetRawQueryByArgs(req.URL.RawQuery, "uid")
	if err != nil || uid == "" {
		lib.HandleError(err)
		w.Write(models.GetErrorResult("参数错误"))
		return
	}

	url :=conf.MicroServerURL()+ "/manage/api/select_build_info?uid="+uid+"&req_token=11qq22e"

	_,testBody, _ ,err:= lib.HttpRequest(url, "GET", nil, nil)
	if err !=nil{
		lib.HandleError(err)
		w.Write(models.GetFalatResult())
		return
	}

	temp := &models.BuildInfo{}
	err = json.Unmarshal(testBody,temp)
	if err != nil {
		lib.HandleError(err)
		w.Write(models.GetErrorResult("转换JSON失败"))
		return
	}

	fmt.Println(temp.Data.Build.Dockerfile_path)

	resModel, err := models.SetResult(200, "succ", temp.Data.Build)
	if err != nil {
		lib.HandleError(err)
		w.Write(models.GetFalatResult())
		return
	}
	w.Write(resModel)
}



func GetRegisterList(w http.ResponseWriter,req *http.Request){
	uid, err := lib.GetRawQueryByArgs(req.URL.RawQuery, "uid")
	if err != nil {
		lib.HandleError(err)
		w.Write(models.GetErrorResult("参数错误"))
		return
	}
	urlPl := conf.MicroServerURL()+ "/manage/api/select_pro_username?request_token=" + "11qq22e"+"&uid="+uid
	_,testBody, _ ,err:= lib.HttpRequest(urlPl, "GET", nil, nil)
	if err !=nil{
		lib.HandleError(err)
		w.Write(models.GetFalatResult())
		return
	}
	resTemp := &models.ApiRes{}
	err = json.Unmarshal(testBody, resTemp)
	if err !=nil{
		lib.HandleError(err)
		w.Write(models.GetErrorResult("转换JSON失败"))
		return
	}
	if len(resTemp.Data.Pro_info)==0{
		lib.HandleError(errors.New("未找到对象"))
		w.Write(models.GetErrorResult("未找到对象"))
		return
	}
	basicAuth := "Basic "+resTemp.Data.Pro_info[0].Pro_username +":"+resTemp.Data.Pro_info[0].Pro_pwd

	res,err:= requestHarborSearch(basicAuth)

	if err !=nil {
		lib.HandleError(err)
		w.Write(models.GetErrorResult(err.Error()))
		return
	}
	resModel, err := models.SetResult(200, "succ", string(res))
	if err != nil {
		lib.HandleError(err)
		w.Write(models.GetFalatResult())
		return
	}
	w.Write(resModel)
}

func requestHarborSearch(basicAuth string) ([]byte,error){
	header  :=make(http.Header)
	header.Set("Authorization","Basic bmloYW84OjEyM3F3ZWFzZA==")
	registerProjectUrl :="https://www.delery.online/api/search"
	codeStatus,res,_,err := lib.HttpRequest(registerProjectUrl,"GET",nil,header)

	if err != nil{
		return nil,err
	}
	if codeStatus != 200{
		return nil,errors.New(string(res))
	}
	maptemp := make(map[string][]models.HarborProject)
	err = json.Unmarshal(res,&maptemp)
	if err!=nil{
		return nil,err
	}
	//fmt.Println(maptemp["repository"])
	record := []map[string]interface{}{}

	for k,_ := range maptemp["repository"]{
		record = append(record,make(map[string]interface{}))
		record[k]["imgName"]=maptemp["repository"][k].Repository_name
		record[k]["public"]=maptemp["repository"][k].Project_public
		record[k]["host"]="www.test.com"+ maptemp["repository"][k].Repository_name
	}
	byteres,err:= json.Marshal(record)
	if err !=nil{
		return nil,err
	}
	return  byteres,nil
}



func StartProject(w http.ResponseWriter,req *http.Request){

}